package com.neuedu.jxcboot.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.neuedu.jxcboot.common.bean.JsonResult;
import com.neuedu.jxcboot.common.bean.Pager;
import com.neuedu.jxcboot.entity.User;
import com.neuedu.jxcboot.service.UserService;
import com.neuedu.jxcboot.util.FileResult;
import com.neuedu.jxcboot.util.FileuploadUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @RestController控制器默认会返回Body
 * @author chens
 *
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserConntroller {

	@Autowired
	private UserService userService;

	@Value("${spring.servlet.multipart.location}")
	private String uploadPath;

	/**
	 * <pre>
	 * 使用方法的参数接收用户输入的参数
	 * 1.使用方法的参数名与页面的参数名一致，接收参数
	 * 2.使用RequestParam指定页面的参数名，接收参数
	 * </pre>
	 * 
	 * @param page 分页页码
	 * @param size 分页大小
	 * @return
	 */
	@RequestMapping("/list")
	public Pager<User> list(@RequestParam(value = "page", defaultValue = "1") Integer page,
			@RequestParam(value = "rows", defaultValue = "10") Integer size) {
		Pager<User> pager = new Pager<>(page, size);

		List<User> list = userService.list(pager);
		int total = userService.count(pager);
		pager.setData(list);
		pager.setTotal(total);

		return pager;
	}

	@RequestMapping("/add")
	public JsonResult add(MultipartFile file1, User user) {
		JsonResult result = new JsonResult(Boolean.FALSE, "新增失败");

		// 先执行文件上传
		if (file1 != null && !file1.isEmpty()) {

			FileResult fileResult = FileuploadUtil.uploadFile(uploadPath, file1);
			if (!fileResult.getSuccess()) {
				return new JsonResult(false, fileResult.getMsg());
			}

			String serverFileString = fileResult.getServerPath();
			// 把上传后的文件地址保存到用户的参数中
			user.setUserImage(serverFileString);
		}

		// 用户注册时，取服务器的系统时间
		user.setUserDate(new Date());

		boolean ret = userService.add(user);
		if (ret) {
			result = new JsonResult(Boolean.TRUE, "新增成功");
		}
		return result;
	}

	@RequestMapping("/edit")
	public JsonResult edit(MultipartFile file1, User user) {
		JsonResult result = new JsonResult(Boolean.FALSE, "修改失败");

		// 先执行文件上传
		if (file1 != null && !file1.isEmpty()) {

			FileResult fileResult = FileuploadUtil.uploadFile(uploadPath, file1);
			if (!fileResult.getSuccess()) {
				return new JsonResult(false, fileResult.getMsg());
			}
			String serverFileString = fileResult.getServerPath();
			// 把上传后的文件地址保存到用户的参数中
			user.setUserImage(serverFileString);
		}
		
		//先上传后更新（保存）
		boolean ret = userService.edit(user);
		if (ret) {
			result = new JsonResult(Boolean.TRUE, "修改成功");
		}
		return result;
	}

	@RequestMapping("delete")
	public JsonResult delete(User user) {
		JsonResult result = new JsonResult(Boolean.FALSE, "删除失败");

		List<User> list = new ArrayList<User>();
		list.add(user);

		boolean ret = userService.deleteByIds(list);
		if (ret) {
			result = new JsonResult(Boolean.TRUE, "删除成功");
		}
		return result;
	}

	/**
	 * spring mvc 可以直接注入HttpServletRequest
	 * 
	 * @param username
	 * @param password
	 * @param validate
	 * @param request
	 * @return
	 */
	@RequestMapping("login")
	public JsonResult login(String username, String password, String validate, HttpServletRequest request,
			HttpServletResponse response) {
		JsonResult result = new JsonResult(Boolean.FALSE, "登录失败");
		// 先进行验证码验证，通过后才进行数据库校验 -- 提高数据库的安全性
		// 取得服务器保存的验证码
		String code = (String) request.getSession().getAttribute("rand");
		if (code != null && code.equalsIgnoreCase(validate)) {
			log.info(username + " +++    " + password);
			User user = userService.login(username, password);
			// 如果用户登录成功，需要在服务器记录当前登录信息，并返回给浏览器客户端
			if (user != null) {
				// 回话跟踪技术传统后两种：session和cookie
				// 服务器使用session进行跟踪
				request.getSession().setAttribute("SESSION_USER", user);

				// 客户端使用cookie进行跟踪
				Cookie cookie = new Cookie("COOKIE_USER", user.getUserName());
				cookie.setPath("/");
				cookie.setMaxAge(7 * 24 * 60 * 60);
				response.addCookie(cookie);
				// 登录成功返回登录成功结果
				result = new JsonResult(Boolean.TRUE, "登录成功");

			} else {
				result = new JsonResult(Boolean.FALSE, "账号或密码错误");
			}
		} else {
			result = new JsonResult(Boolean.FALSE, "验证码错误");
		}
		return result;
	}
	
	
	@RequestMapping("logout")
	public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//清除session回话
		request.getSession().invalidate();
		
		//删除cookie信息
		Cookie cookie = new Cookie("COOKIE_USER", "");
		cookie.setPath("/");
		cookie.setMaxAge(0);
		response.addCookie(cookie);
			
		response.sendRedirect("/login.html");
		
	}

}
